package com.changgou.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.changgou.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @ClassName: OrderPayMessageListener
 * @Author: ZWJ
 * @Date: 2020-09-09 14:31
 * @Synopsis: Null
 **/
@Component
public class OrderPayMessageListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = "queue.order")
    private void consumeMessage(String msg, Channel channel, Message message){
        //try {
            //将回调的数据转换成map
            Map<String,String> map = JSONObject.parseObject(msg, Map.class);
            //判断订单的交易详情
            //判断返回状态码
            String return_code = map.get("return_code").toString();
            if("SUCCESS".equals(return_code)){
                //判断业务结果
                String result_code = map.get("result_code").toString();
                String out_trade_no = map.get("out_trade_no").toString();
                if ("SUCCESS".equals(result_code)){
                    //有订单号等详细信息返回,支付成功，修改订单状态
                    String transaction_id = map.get("transaction_id").toString();
                    orderService.updateStatus(out_trade_no,transaction_id);
                }else {
                    //支付失败修改订单状态
                    orderService.deleteOrder(out_trade_no);
                }
            }
           // channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
       // } catch (IOException e) {
         //   e.printStackTrace();
          //  try {
          //      channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
           // } catch (IOException e1) {
            //    e1.printStackTrace();
           // }
        //}
    }
}
